//package com.my.login;
//
//import cn.binarywang.wx.miniapp.api.WxMaService;
//import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
//import cn.hutool.core.util.ObjectUtil;
//import com.alibaba.fastjson.JSON;
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import io.swagger.annotations.ApiOperation;
//import io.swagger.annotations.ApiResponse;
//import lombok.extern.slf4j.Slf4j;
//import me.chanjar.weixin.common.error.WxErrorException;
//import org.apache.commons.lang3.StringUtils;
//import org.jeecg.common.api.vo.Result;
//import org.jeecg.common.constant.CommonConstant;
//import org.jeecg.common.system.util.JwtUtil;
//import org.jeecg.common.util.PasswordUtil;
//import org.jeecg.common.util.RedisUtil;
//import org.jeecg.common.util.oConvertUtils;
//import org.jeecg.modules.app.service.IWeiXinMiniService;
//import org.jeecg.modules.app.vo.MiniPhoneNumberReqVo;
//import org.jeecg.modules.app.vo.MiniProLoginReqVo;
//import org.jeecg.modules.app.vo.MiniUserReqVo;
//import org.jeecg.modules.app.vo.WeChatClientInfoRespVo;
//import org.jeecg.modules.constant.RedisConstants;
//import org.jeecg.modules.constant.UserConstants;
//import org.jeecg.modules.system.entity.SysUser;
//import org.jeecg.modules.system.entity.SysUserRole;
//import org.jeecg.modules.system.mapper.SysUserRoleMapper;
//import org.jeecg.modules.system.service.ISysUserService;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.data.redis.core.RedisTemplate;
//import org.springframework.validation.annotation.Validated;
//import org.springframework.web.bind.annotation.*;
//
//import javax.annotation.Resource;
//import java.util.UUID;
//import java.util.concurrent.TimeUnit;
//
///**
// * Created by ljz
// * 2017-07-03 01:20
// */
//@RestController
//@RequestMapping("/wechat")
//@Slf4j
//public class WechatController {
//
//    @Resource
//    private RedisTemplate<String, String> redisTemplate;
//    @Resource
//    private WxMaService wxMaService;
//
//    @Autowired
//    private ISysUserService userService;
//
//    @Autowired
//    private IWeiXinMiniService weiXinMiniService;
//
//    @Autowired
//    private RedisUtil redisUtil;
//
//    @Autowired
//    private SysUserRoleMapper sysUserRoleMapper;
//
//    //    @GetMapping("/auth")
////    public void userInfo(String code,String encryptedData,String iv) throws WxErrorException {
////        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
////        wxMaService.getUserService().getPhoneNoInfo(sessionInfo.getSessionKey(),encryptedData,iv);
////        String decrypt = AESUtils.decrypt(encryptedData, sessionInfo.getSessionKey(), iv);
////        wxMaService.getUserService().getUserInfo(sessionInfo.getSessionKey(),encryptedData,iv);
////        System.out.println("解密后:" + decrypt);
////    }
//    @ApiOperation(value = "微信小程序登陆接口", notes = "微信小程序登陆接口", response = WeChatClientInfoRespVo.class)
//    @PostMapping("/userInfo")
//    public Result<WeChatClientInfoRespVo> userInfo(@RequestBody @Validated MiniProLoginReqVo reqVo) throws WxErrorException {
//
//        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(reqVo.getCode());
//
//        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(SysUser::getOpenId, sessionInfo.getOpenid());
//        SysUser user = userService.getOne(queryWrapper);
//        if (ObjectUtil.isNull(user)) {
//            // 创建用户并返回token
//            String avatar = "http://api.multiavatar.com/" + (int) (Math.random() * 100) + ".png";
//            user = new SysUser();
//            user.setUsername("minAppName" + (int) (Math.random() * 1000));
//
//            String salt = oConvertUtils.randomGen(8);
//            user.setSalt(salt);
//            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), "123456", salt);
//            user.setPassword(passwordEncode);
//            user.setAvatar(avatar);
//            user.setStatus(1);
//            if (reqVo.getSex() != null) {
//                user.setSex(reqVo.getSex());
//            }
//            user.setNickName(StringUtils.isEmpty(reqVo.getNickName()) ? null : reqVo.getNickName());
//            user.setOpenId(sessionInfo.getOpenid());
//            userService.save(user);
//
//            //设置默认角色
//            SysUserRole userRole = new SysUserRole(user.getId(), "f6817f48af4fb3af11b9e8bf182f618b");
//            sysUserRoleMapper.insert(userRole);
//
//            WeChatClientInfoRespVo clientRespVo = new WeChatClientInfoRespVo();
//            clientRespVo.setId(user.getId());
//            clientRespVo.setHeadImg(user.getAvatar());
//            clientRespVo.setNickName(StringUtils.isEmpty(user.getNickName()) ? null : user.getNickName());
//            clientRespVo.setName(StringUtils.isEmpty(user.getRealname()) ? null : user.getRealname());
//            clientRespVo.setPhone(StringUtils.isEmpty(user.getPhone()) ? null : user.getPhone());
//            clientRespVo.setToken(UUID.randomUUID().toString());
//            clientRespVo.setIsBinding(StringUtils.isEmpty(user.getPhone()) ? 0 : 1);
//            if (user.getSex() != null) {
//                clientRespVo.setSex(user.getSex());
//            }
//            clientRespVo.setOpenId(user.getOpenId());
//
//            redisTemplate.opsForValue().set(RedisConstants.redis_mini_token + clientRespVo.getToken(),
//                    JSON.toJSONString(clientRespVo), UserConstants.PWD_EXPIRE_DAYS, TimeUnit.DAYS);
//
//            // 更新或者保存一下小程序 sessionKey ，key=tokenid+用户id 唯一
//            log.info("session_key:{}", sessionInfo.getSessionKey());
//            redisTemplate.opsForValue().set(RedisConstants.redis_mini_token + clientRespVo.getId(), sessionInfo.getSessionKey());
//
//            //1.生成token
//            String token = JwtUtil.sign(user.getUsername(), user.getPassword());
//            // 设置token缓存有效时间
//            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
//            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
//            clientRespVo.setToken(token);
//            return Result.OK(clientRespVo);
//        } else {
//            // 已经存在
//            // 客户信息
//            WeChatClientInfoRespVo clientRespVo = new WeChatClientInfoRespVo();
//            clientRespVo.setId(user.getId());
//            clientRespVo.setOpenId(user.getOpenId());
//            clientRespVo.setHeadImg(user.getAvatar());
//            clientRespVo.setNickName(StringUtils.isEmpty(user.getNickName()) ? null : user.getNickName());
//            clientRespVo.setPhone(StringUtils.isEmpty(user.getPhone()) ? null : user.getPhone());
//            //1.生成token
//            String token = JwtUtil.sign(user.getUsername(), user.getPassword());
//            // 设置token缓存有效时间
//            redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
//            redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
//            clientRespVo.setToken(token);
//            if (user.getSex() != null) {
//                clientRespVo.setSex(user.getSex());
//            }
//            clientRespVo.setIsBinding(StringUtils.isEmpty(user.getPhone()) ? 0 : 1);
//            redisTemplate.opsForValue().set(RedisConstants.redis_mini_token + clientRespVo.getToken(),
//                    JSON.toJSONString(clientRespVo), UserConstants.PWD_EXPIRE_DAYS, TimeUnit.DAYS);
//
//            // 更新或者保存一下小程序 sessionKey ，key=tokenid+用户id 唯一
//            log.info("session_key:{}", sessionInfo.getSessionKey());
//            redisTemplate.opsForValue().set(RedisConstants.redis_mini_token + clientRespVo.getId(), sessionInfo.getSessionKey());
//
//
//            return Result.OK(clientRespVo);
//        }
//
//    }
//
//    // 2 微信小程序获取手机号绑定
//    @ApiOperation(value = "微信小程序获取手机号绑定接口", notes = "微信小程序获取手机号绑定接口", response = WeChatClientInfoRespVo.class)
//    @ApiResponse(response = WeChatClientInfoRespVo.class, code = 200, message = "接口返回对象参数")
//    @RequestMapping(value = "/getPhoneNumber", method = RequestMethod.POST)
//    public Result<WeChatClientInfoRespVo> getPhoneNumber(@RequestBody @Validated MiniPhoneNumberReqVo reqVo) {
//        log.info("getPhoneNumber--->:{}", JSON.toJSONString(reqVo));
//        WeChatClientInfoRespVo respVo = weiXinMiniService.getPhoneNumber(reqVo);
//        return Result.ok(respVo);
//    }
//
//    @ApiOperation(value = "退出接口", notes = "退出接口")
//    @ApiResponse(code = 200, message = "接口返回对象参数")
//    @RequestMapping(value = "/loginOut/{token}", method = RequestMethod.GET)
//    public Result loginOut(String token) {
//        log.info("loginOut--->:{}", token);
//        weiXinMiniService.loginOut(token);
//        return Result.ok();
//    }
//
//    // 2 微信小程序获取手机号绑定
//    @ApiOperation(value = "微信小程序个人信息接口", notes = "微信小程序个人信息接口", response = WeChatClientInfoRespVo.class)
//    @ApiResponse(response = WeChatClientInfoRespVo.class, code = 200, message = "接口返回对象参数")
//    @RequestMapping(value = "/updateUserInfo", method = RequestMethod.POST)
//    public Result<WeChatClientInfoRespVo> updateUserInfo(@RequestBody @Validated MiniUserReqVo reqVo) {
//        log.info("getPhoneNumber--->:{}", JSON.toJSONString(reqVo));
//        WeChatClientInfoRespVo weChatClientInfoRespVo = weiXinMiniService.updateUserInfo(reqVo);
//        return Result.ok(weChatClientInfoRespVo);
//    }
//
//}
